/*
 * payment DAO.java
 *
 * Created on February 13, 2007
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

/**
 * Version 1.0
 *
 * The data base access object for payments
 */
package finalintex2web;
import java.util.*;
import java.io.*;
import java.sql.*;

/**
 * database access object for payments
 */
public class PaymentDAO {
    
    
    ///////////////////////////////////////
    ///   Singleton pattern
    
    private static PaymentDAO instance = null;
    
    /** Creates a new instance of PaymentDAO */
    private PaymentDAO() {
    }
    
    /**
     * 
     * @return 
     */
    public static synchronized PaymentDAO getInstance() {
        if (instance == null) {
            instance = new PaymentDAO();
        }
        return instance;
    }
    
    
    /////////////////////////////////
    ///   CREATE
     
    /**
     *  creates new Payment
     *  @return PaymentBO
     */
    public PaymentBO create() {
        String id = GUID.generate();
        PaymentBO pay = new PaymentBO(id);
        Cache c = Cache.getInstance();
        c.put(pay.getId(), pay);
        return pay;
    }
    
    
    /////////////////////////////////////
    ///   READ
   /**
     *  reads object from database
     *  @return PaymentBO
     *  @param  id is the object id
     */
    public synchronized PaymentBO read(String id) throws DataException,ConnectionPoolException {
        if(Cache.getInstance().containsKey(id)){
            PaymentBO pay = (PaymentBO)Cache.getInstance().get(id);
            return pay;
        }
        
        try {
            Connection conn = ConnectionPool.getInstance().get();
            PaymentBO pay = (PaymentBO)read(id,conn);
            ConnectionPool.getInstance().release(conn);
            return pay;
        }catch (SQLException e) {
            // rollback
            throw new DataException("SQL error from read 1", e);
        }catch (ConnectionPoolException e){
            throw new ConnectionPoolException("Connection pool error in read 1", e);
        }
        
     
    }
    
    /** 
     *  This is a package method that is called by the public read (above) or
     *  by another DAO.  Either way we already have a connection to the database
     *  to use.  The user (controller) code never calls this one directly, since
     *  it can't know about Connection PaymentDBOs or SQLExceptions.
     *  @param id is the object id 
     *  @param conn in the database connection
     */
    public synchronized PaymentBO read(String id, Connection conn) throws SQLException, DataException, ConnectionPoolException {
            if(Cache.getInstance().containsKey(id)){
            PaymentBO pay = (PaymentBO)Cache.getInstance().get(id);
            return pay;
            } 
                
           try{        
           PreparedStatement stmt = conn.prepareStatement("SELECT * FROM Payment WHERE id=?");
           stmt.setString(1,id);
           ResultSet rs =  stmt.executeQuery();
           
           ConnectionPool.getInstance().release(conn);
            
            if (rs.next()) {
                PaymentBO pay = new PaymentBO(id);
                pay.setAmount(rs.getDouble("amount"));
                pay.setChange(rs.getDouble("change"));
                pay.setType(rs.getString("type"));
                Cache.getInstance().put(id,pay);      
                pay.setIndb(true);
                stmt.close();
                return pay;
               

            }else{
                throw new DataException("PaymentBO was not found in the database.");
            }
           
            }catch (ConnectionPoolException e){
                throw new ConnectionPoolException("Could not retrieve a connection from the database", e);
            
            }catch (SQLException e){
                throw new DataException("SQL error", e);
            }
            
    }
        
    
    
    //////////////////////////////////
    ///   UPDATE
    
    /** 
     * This is the public save method.  It is what is called when
     * the user (controller) code wants to save or update an PaymentDBO
     * into the database.
     * @param pay is the object to be saved to teh database
     */
    public synchronized void save(PaymentBO pay) throws DataException,ConnectionPoolException {
        
        
        try {
            Connection conn = ConnectionPool.getInstance().get();
            save(pay,conn);
            ConnectionPool.getInstance().release(conn);
        }catch (SQLException e) {
            //rollback
            throw new DataException("Could not retrieve record for id=" + pay.getId(), e);
            
            }catch (ConnectionPoolException e){
            throw new ConnectionPoolException("Could not retrieve record for id=" + e);
        }
        
        // release the connection back to the pool
        return;
    }
    
    /** 
     *  This is a package method that is called by the public save (above) or
     *  by another DAO.  Either way we already have a connection to the database
     *  to use.  The user (controller) code never calls this one directly, since
     *  it can't know about Connection PaymentDBOs or SQLExceptions.
     *
     *  By having other DAOs call this save method (rather than update or
     *  insert below, each DAO in a chained save (like the PaymentDAO calling
     *  MembershipDAO calling InterestDAO save chain) can independently decide
     *  whether to udpate or insert the BO it's saving.  That's why I made
     *  update and insert private rather than package level -- if you call
     *  them directly from another DAO, this DAO can't decide whether it's
     *  PaymentDBO needs to be inserted or updated.
     */
     synchronized void save(PaymentBO pay, Connection conn) throws SQLException, DataException, ConnectionPoolException {
        // check the dirty flag in the PaymentDBO.  if it is dirty, 
        // run update or insert
        if (pay.isDirty()) {
            if (pay.isIndb()) {
                update(pay, conn);
            }else{
                insert(pay, conn);
            }
            pay.setDirty(false);
        
        
        Cache.getInstance().touch(pay.getId());
     
        }
        
    }
    
    /**
     * This method is really a part of save(bo, conn) above.  It could be
     * embedded directly in it, but I've separated it into it's own method
     * to isolate the SQL udpate statement and make it more readable.  But
     * logically, it's really just a part of save.
     */
    private synchronized void update(PaymentBO pay, Connection conn) throws SQLException, DataException, ConnectionPoolException {
        PreparedStatement stmt = conn.prepareStatement("UPDATE Payment SET amount = ?, change = ?, paymenttype = ?, transactionid = ? WHERE id=? ");
        stmt.setDouble(1,pay.getAmount());
        stmt.setDouble(2,pay.getChange());
        stmt.setString(3,pay.getType());
        stmt.setString(4,pay.getTransaction().getId());
        stmt.setString(5,pay.getId());
        stmt.execute();
        stmt.close();
        ConnectionPool.getInstance().release(conn);
    }
     
    /**
     * This method is really a part of save(bo, conn) above.  It could be
     * embedded directly in it, but I've separated it into it's own method
     * to isolate the SQL insert statement and make it more readable.  But
     * logically, it's really just a part of save.
     */
    private synchronized void insert(PaymentBO pay, Connection conn) throws SQLException, DataException, ConnectionPoolException {
        // do the insert SQL statement
        PreparedStatement stmt = conn.prepareStatement("INSERT INTO Payment (amount,change,paymenttype,transactionid,id) VALUES ( ?,?,?,?,?)");
        stmt.setDouble(1,pay.getAmount());
        stmt.setDouble(2,pay.getChange());
        stmt.setString(3,pay.getType());
        stmt.setString(4,pay.getTransaction().getId());
        stmt.setString(5,pay.getId());
        stmt.execute();
        stmt.close();
        // tell the PaymentDBO that it's now in the db (so we call update next time not insert)
        pay.setIndb(true);
        ConnectionPool.getInstance().release(conn);
    }
    
    
    ////////////////////////////////////
    ///   DELETE
    // We are not implementing this feature in this class to help preserve data intergity.

}